package com.rainng.coursesystem.service;

import com.rainng.coursesystem.model.FavouriteItem;
import com.rainng.coursesystem.repository.FavouriteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Service
public class FavouriteService {

    @Autowired
    private FavouriteRepository favouriteRepository;

    @Value("${file.upload-dir}")
    private String uploadDir;

    public String uploadAndAddToFavourites(String sNumber, String tNumber, MultipartFile file, boolean isPublic) throws Exception {
        UUID newFileId = UUID.randomUUID();

        if (favouriteRepository.existsBysNumberAndFileName(sNumber, tNumber, file.getOriginalFilename())) {
            throw new Exception("文件已收藏");
        }

        String fileName = newFileId.toString() + "_" + file.getOriginalFilename();
        Path copyLocation = Paths.get(uploadDir, fileName);
        Files.createDirectories(copyLocation.getParent());
        Files.copy(file.getInputStream(), copyLocation);

        FavouriteItem item = new FavouriteItem();
        item.setFileId(newFileId);
        if (sNumber != null) {
            item.setsNumber(sNumber);
        }
        if (tNumber != null) {
            item.settNumber(tNumber);
        }
        item.setFileName(file.getOriginalFilename());
        item.setFileData(copyLocation.toString());
        item.setIsPublic(isPublic);
        item.setLikesCount(0);

        favouriteRepository.save(item);
        return "文件上传并添加到收藏夹成功！";
    }

    // 根据文件 ID 获取收藏
    public FavouriteItem getFavouriteById(UUID fileId) {
        return favouriteRepository.findByFileId(fileId).orElse(null);
    }

    public void removeFavourite(UUID fileId) throws IOException {
        Optional<FavouriteItem> optionalItem = favouriteRepository.findByFileId(fileId);

        if (optionalItem.isPresent()) {
            FavouriteItem item = optionalItem.get();
            Path filePath = Paths.get(item.getFileData());
            Files.deleteIfExists(filePath);
            favouriteRepository.delete(item);
        } else {
            throw new IOException("在收藏夹中找不到该文件");
        }
    }

    public List<FavouriteItem> listFavourites(String sNumber, String tNumber) {
        return favouriteRepository.findBysNumberOrtNumber(sNumber, tNumber);
    }

    public List<FavouriteItem> listPublicFavourites(String sNumber, String tNumber) {
        return favouriteRepository.findPublicFavouritesExcludingUser(sNumber, tNumber);
    }

    public boolean setFavouriteVisibility(String sNumber, String tNumber, Boolean isPublic) {
        List<FavouriteItem> items = favouriteRepository.findBysNumberOrtNumber(sNumber, tNumber);
        if (items.isEmpty()) {
            return false;
        }
        items.forEach(item -> item.setIsPublic(isPublic));
        favouriteRepository.saveAll(items);
        return true;
    }

    // 收藏点赞
    public boolean likeFavourite(UUID fileId) {
        System.out.println(fileId);
        return favouriteRepository.findByFileId(fileId).filter(FavouriteItem::isPublic).map(item -> {
            item.setLikesCount(item.getLikesCount() + 1);
            favouriteRepository.save(item);
            return true;
        }).orElse(false);
    }
}